<!DOCTYPE html>
<html lang="en">
  <head>
    <title>MVC框架</title>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <style>
      .box {
        display: flex;
        align-items: center;
      }
      .splice {
        width: 1rem;
      }
    </style>
  </head>
  <body>
    <div id="app"></div>

    <script>
      // mvc
      (function () {
        function init() {
          model.init();
          view.render();
          controller.init();
        }

        const model = {
          data: {
            name: "橘子哥哥",
            age: 19,
          },
          init() {
            for (let key in this.data) {
              Object.defineProperty(this, key, {
                get() {
                  return this.data[key];
                },
                set(newValue) {
                  this.data[key] = newValue;
                  view.render({ [key]: newValue }); // ❌
                },
              });
            }
          },
        };

        const view = {
          el: "#app",
          template: `
            <div class="box">
              <div class="cal-name">{{ name }}</div>
              <div>,今年</div>
              <div class="cal-age">{{ age }}</div>
              <div>岁</div>
              <div class="splice"></div>
              <button class="cal-button add">+</button>
              <button class="cal-button reduce">-</button>
            </div>
          `,
          reg: /\{\{(.*?)\}\}/g,
          render(mutedData) {
            if (!mutedData) {
              this.template = this.template.replace(this.reg, (node, key) => {
                return model[key.trim()];
              });
              const container = document.createElement("div");
              container.innerHTML = this.template;
              document.querySelector(this.el).appendChild(container);
            } else {
              for (const key in mutedData) {
                document.querySelector(`.cal-${key}`).textContent =
                  mutedData[key];
              }
            }
          },
        };

        const controller = {
          init() {
            const oCalButtons = document.querySelectorAll(".cal-button");

            for (let i = 0; i < oCalButtons.length; i++) {
              btnItem = oCalButtons[i];
              btnItem.addEventListener("click", this.handleBtnClick, false);
            }
          },
          handleBtnClick(e) {
            switch (e.target.textContent) {
              case "+":
                model.age++;
                break;
              case "-":
                model.age--;
                break;
              default:
                break;
            }
          },
        };
        init();
      })();
    </script>
  </body>
</html>
